import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Table,
  Button,
  Input,
  Modal,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import AddWhiteList from './components/AddWhiteList';
import ImportWhiteList from './components/ImportWhiteList';

const { pathname } = window.location;

interface CabinetDeliveryWhitelistProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  screen: string;
}

interface CabinetDeliveryWhitelistState {
  searchValues: any;
  addVisible: boolean;
  importVisible: boolean;
  delVisible: boolean;
  delId: number;
  pageIndex:number;
  pageSize:number;
  rowId:number;
}

@connect(({
  cabinetDeliveryWhitelist: { dataInfo },
  global: { screen },
  loading,
}: any) => ({
  dataInfo,
  screen,
  loading: loading.effects['cabinetDeliveryWhitelist/fetch'],
}))
class CabinetDeliveryWhitelistElem extends Component<CabinetDeliveryWhitelistProps,
CabinetDeliveryWhitelistState> {
  columns = [
    { title: '柜体编号', dataIndex: 'cabinetCode' },
    { title: '手机号', dataIndex: 'consigneePhone' },
    { title: '添加人', dataIndex: 'createUserName' },
    { title: '添加时间', dataIndex: 'createTime' },
    {
      title: '操作',
      width: 100,
      render: (val: any, row: any) => (
        <span className="operLink" onClick={() => this.handleChangeDelModal(true, row.id)}>
          删除
        </span>
      ),
    },
  ];

  state: CabinetDeliveryWhitelistState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    addVisible: false,
    importVisible: false,
    delVisible: false,
    delId: 0,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '柜体投递白名单',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体投递白名单',
      url: pathname,
      isTopMenu: true,
    });
  };

  changeAddWhiteListModal = (addVisible: boolean) => this.setState({ addVisible });

  changeImportWhiteListModal = (importVisible: boolean) => this.setState({ importVisible });

  handleChangeDelModal = (delVisible: boolean, delId: number = 0) => {
    this.setState({ delVisible, delId });
  };

  handleDelSure = () => {
    const { delId: id, searchValues: search } = this.state;
    const params = { search, id };
    this.fetchAction('delete', params);

    this.handleChangeDelModal(false);
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体投递白名单',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    // 张倩  2020-9-10 修改
    if (typeName === 'addWhiteList') {
      const { searchValues: search } = this.state;
      payload = { search, ...payload };
    }

    const { dispatch } = this.props;
    dispatch({
      type: `cabinetDeliveryWhitelist/${typeName}`,
      payload,
    });
  };

  render() {
    const {
      addVisible,
      importVisible,
      delVisible,
      pageIndex,
      pageSize,
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      loading,
    } = this.props;

    const dataSource = dataInfo.list || [];

    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={6} sm={24}>
                <Form.Item label="柜体编号" colon={false}>
                  {getFieldDecorator('cabinetCode')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="手机号码" colon={false}>
                  {getFieldDecorator('consigneePhone')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.changeAddWhiteListModal(true)}
            >
              添加白名单
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={() => this.changeImportWhiteListModal(true)}
            >
              批量导入白名单
            </Button>
          </div>

          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
        <AddWhiteList
          AddVisible={addVisible}
          FetchAction={this.fetchAction.bind(this)}
          ChangeAddWhiteListModal={this.changeAddWhiteListModal.bind(this)}
        />
        <ImportWhiteList
          ImportVisible={importVisible}
          FetchAction={this.fetchAction.bind(this)}
          ChangeImportWhiteListModal={this.changeImportWhiteListModal.bind(this)}
        />
        <Modal
          title="删除提示"
          visible={delVisible}
          okText="删除"
          onOk={this.handleDelSure}
          onCancel={() => this.handleChangeDelModal(false)}
        >
          <p style={{ textAlign: 'center' }}>确定删除当前白名单吗？</p>
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<CabinetDeliveryWhitelistProps>()(CabinetDeliveryWhitelistElem);
